<?php

//@include('connect/connect_mysql.php');
@include('../connect/connect_mysql.php');
include('json.php');

$icon;
$description;
// Future-friendly json_encode
if( !function_exists('json_encode') ) {
    function json_encode($data) {
        $json = new Services_JSON();
        return( $json->encode($data) );
    }
}
 
// Future-friendly json_decode
if( !function_exists('json_decode') ) {
    function json_decode($data) {
        $json = new Services_JSON();
        return( $json->decode($data) );
    }
}


$images = array();
$query_nearest_event = "SELECT * FROM event e WHERE DATE(e.date) <= DATE(NOW()) and is_deleted = 0 ORDER BY DATE(e.date) DESC LIMIT 1";
$query_nearest_event1 = "SELECT * FROM event e WHERE DATE(e.date)>= DATE(NOW()) and is_deleted = 0 ORDER BY DATE(e.date) ASC LIMIT 1";
$events_in_month = array();
$events_by_day = array();

if(isset($_POST['mode']) && !empty($_POST['mode']))
{
    $mode = $_POST['mode'];
    switch ($mode){
        case 1: //load calendar
            load_calendar();
            break;
        case 2: //load event
            load_event();
            break;
        default: //initialize whole page
            initialize_page();
    }
}else
    initialize_page();


function initialize_page()
{
    global $events_by_day;
    global $query_nearest_event;
	global $query_nearest_event1;
    $date = time () ;
	$eventid = 1;
    mysql_query ("SET NAMES 'utf8'");
    $result = mysql_query($query_nearest_event);
    @$num_rows = mysql_num_rows($result);
    if($num_rows == 0) {
	    mysql_query ("SET NAMES 'utf8'");
		$result = mysql_query($query_nearest_event1);
		$row = mysql_fetch_array($result);
		@$num_rows = mysql_num_rows($result);
		if($num_rows != 0){
			$str_date = $row['date'];
			$img_path = $row['path'];
			$info = $row['info'];
			$date = strtotime($str_date);
			$eventid = $row['event_id'];
		}
    } else {
        $row = mysql_fetch_array($result);
        $str_date = $row['date'];
        $img_path = $row['path'];
        $info = $row['info'];
        $date = strtotime($str_date);
		$eventid = $row['event_id'];
    }
    $day = date('d', $date) ;
    $month = date('m', $date);
    $year = date('Y',$date);
    $str_calendar = reload_calendar($month, $year);
	$albumdata = load_eventalbum($eventid);
    $page_data = array("calendar" => $str_calendar,
                        "path" => $img_path, //path to event logo image
                        "info" => $info,
						"month" => $month,
						"year" => $year,
                        "albumdata" => $albumdata,
                        "contextmenudata" => $events_by_day);
    echo (json_encode($page_data));
    //render_calendar($str);
}

function get_events($month, $year)
{
    global $events_in_month;
    $days_in_month = cal_days_in_month(0, $month, $year);
    $first_day_in_month = $year . "-" . $month . "-01";
    $last_day_in_month = $year . "-" . $month . "-" . $days_in_month;
    $query = "Select * from event WHERE date >= '".$first_day_in_month."' AND date <= '".$last_day_in_month ."' AND is_deleted ='0'"  ;
    mysql_query ("SET NAMES 'utf8'");
    $result = mysql_query($query);
    @$num_rows = mysql_num_rows($result);
    if($num_rows == 0) {
        
    } else {
        while($row = mysql_fetch_array($result))
        {
            $event = array("event_id" => $row['event_id'],
                           "date" => $row['date'],
                           "name" => $row['name'],
                           "path" => $row['path'],
                           "info" => $row['info'],
                           "time" => $row['time']);
            $events_in_month[] = $event;
        }
    }
    return $events_in_month;
}

///Check whether the selected day has events
function has_event($day, $month, $year)
{
    global $events_in_month;
    $event_strdate;
    $event_date;
    $check_strdate = $year."-".$month."-".$day;
    $check_date = strtotime($check_strdate);
    $count = count($events_in_month);
    for ($i = 0; $i < $count; $i++) {
        $event_strdate = $events_in_month[$i]['date'];
        $event_date = strtotime($event_strdate);
        if ($event_date == $check_date)
        {
            return true;
        }
    }
    return false;
}

function get_events_of_day($day, $month, $year)
{
	global $events_in_month;
	$events_of_day = array();
    $event_strdate;
    $event_date;
    $check_strdate = $year."-".$month."-".$day;
    $check_date = strtotime($check_strdate);
    $count = count($events_in_month);
    for ($i = 0; $i < $count; $i++) {
        $event_strdate = $events_in_month[$i]['date'];
        $event_date = strtotime($event_strdate);
        if ($event_date == $check_date)
        {
			$event = $events_in_month[$i];
            $events_of_day[] = $event;
        }
    }
    
    return $events_of_day;
}

function build_calendar($month, $year)
{
	global $events_in_month;
    global $events_by_day;
    get_events($month,$year);
    $str = "";
    //$month = date('m', $date) ;
    //$year = date('Y', $date) ;
    $first_day = mktime(0,0,0,$month, 1, $year) ;
    $title = strtoupper(date('F', $first_day)) ; //Get the month name
    $day_of_week = date('D', $first_day) ;

    //count blank before first day of the month
    switch($day_of_week){
        case "Sun": $blank = 0; break;
        case "Mon": $blank = 1; break;
        case "Tue": $blank = 2; break;
        case "Wed": $blank = 3; break;
        case "Thu": $blank = 4; break;
        case "Fri": $blank = 5; break;
        case "Sat": $blank = 6; break;
    }

    $days_in_month = cal_days_in_month(0, $month, $year);

    $str.= "<table class=\"calendar\" width=170>";
    $str.= "<tr><td colspan=7 ><span style=\"font-weight: bold\">. $title</span></td></tr>";
    //echo "<tr><td width=24>S</td><td width=24>M</td><td
    //    width=24>T</td><td width=24>W</td><td width=24>T</td><td
    //   width=24>F</td><td width=24>S</td></tr>";
    $day_count = 1;
    $str.= "<tr>";

    //first take care of those blank days
    while ( $blank > 0 )
    {
        $str.= "<td></td>";
        $blank = $blank-1;
        $day_count++;
    }

    //sets the first day of the month to 1
    $day_num = 1;
    //count up the days, untill we've done all of them in the month
    while ( $day_num <= $days_in_month )
    {
        if (has_event($day_num, $month,$year))
        {
            $key = $day_num.$month;
            $events_of_day = get_events_of_day($day_num, $month, $year);
            $events_by_day[$key] = $events_of_day;
            $str.="<td><a id=\"calendar$key\" style=\"color: red; font-weight: bold\" rel=\"$key\" href=\"javascript:ContextShow('calendar$key')\"> $day_num </a></td>";
        }else
        {
            $str.= "<td> $day_num </td>";
        }
        $day_num++;
        $day_count++;
        //Make sure we start a new row every week
        if ($day_count > 7)
        {
            $str.= "</tr><tr>";
            $day_count = 1;
        }
    }
    //Finaly finish out the table with some blank details if needed
    while ( $day_count >1 && $day_count <=7 )
    {
        $str.= "<td> </td>";
        $day_count++;
    }
    $str.= "</tr></table>";
    return $str;
}

function initialize_calendar()
{
    global $query_nearest_event;
    $date =time () ;
    mysql_query ("SET NAMES 'utf8'");
    $result = mysql_query($query_nearest_event);
    @$num_rows = mysql_num_rows($result);
    if($num_rows == 0) {

    } else {
        $row = mysql_fetch_array($result);
        $str_date = $row['date'];
        $date = strtotime($str_date);
    }
    $day = date('d', $date) ;
    $month = date('m', $date);
    $year = date('Y',$date);
    $nextmonth = $month + 1;
    $nextyear = $year;
    if($month == 12)
    {
        $nextmonth = 1;
        $nextyear = $year + 1;
    }
    $str = "<p class=\"titlebar\">&nbsp;&nbsp;&nbsp;&nbsp;CALEANDAR</p>";
    $str.=build_calendar($month, $year);
    $str.="</br>";
    $str.=build_calendar($nextmonth, $nextyear);
    return $str;
}

function reload_calendar($month, $year)
{
	global $events_in_month;
    global $events_by_day;
	$events_in_month = array();
    $events_by_day = array();
	$nextmonth = $month + 1;
    $nextyear = $year;
    if($month == 12)
    {
        $nextmonth = 1;
        $nextyear = $year + 1;
    }
    $str = "<p class=\"titlebar\">&nbsp;&nbsp;&nbsp;&nbsp;CALEANDAR</p>";
    $str.=build_calendar($month, $year);
    $str.="</br>";
    $str.=build_calendar($nextmonth, $nextyear);
    return $str;
}

///logo: path to img logo
///info: content of event
///images: array stores images of the event
function build_eventarray()
{
    global $events_in_month;
    //$str = '<script type= "text/javascript">';
	$str = "{\n";
	$str .= "  logo: \"\",\n";
	$str .= "  images: [\n";
    $count = count($events_in_month);
    for ($i = 0; $i < $count; $i++) {
        $str .= "[";
        $event_strdate = $events_in_month[$i]['date'];
        $event_date = strtotime($event_strdate);
        if ($event_date == $check_date)
        {
            return true;
        }
    }
}

function build_contextmenu()
{
    global $events_by_day;
    echo(json_encode($events_by_day));
}

///return a string representing all events in a specific day
///return format: "[{name, time, id},{name, time, id}, {name, time, id}, {name, time, id}]"
function get_eventinfo($day, $month, $year)
{
	global $events_in_month;
	$str = "[";
	$events_of_day = array();
	$events_of_day = get_events_of_day($day, $month, $year);
	echo(json_encode($events_of_day)); 
}



function load_calendar()
{
    if(isset($_POST['month']) && !empty($_POST['month'])
        && isset($_POST['year']) && !empty($_POST['year'])) {
        $month = $_POST['month'];
        $year = $_POST['year'];
        $str = reload_calendar($month, $year);
        render_calendar($str);
    }else{
        $str = initialize_calendar();
        render_calendar($str);
    }
}

function render_calendar($str_calendar)
{
    global $events_by_day;
    $return_value = array("calendar" => $str_calendar,
                           "contextmenudata" => $events_by_day);
    echo(json_encode($return_value));
}

function load_event()
{
    if(isset($_POST['eventid']))
    {
        $eventid = $_POST['eventid'];
        $query = $query = "SELECT * FROM event WHERE event_id = $eventid  and is_deleted = 0";
        mysql_query ("SET NAMES 'utf8'");
        $result = mysql_query($query);
        //@$num_rows = mysql_num_rows($result);
        $row = mysql_fetch_array($result); //
		$albumdata = load_eventalbum($eventid);
        $return_data = array("path" => $row['path'],
                       "info" => $row['info'],
					   "albumdata" => $albumdata);
        echo (json_encode($return_data));
    }
}
//$a = load_eventalbum(5);
//echo (json_encode($a));

function load_eventalbum($eventid)
{
	$array_images = array();
	$query = "Select * from image WHERE page_id = '5' AND event_id = '$eventid' AND is_deleted = '0'";
	$pattern="\.(jpg|jpeg|png|gif|bmp)$";
	mysql_query ("SET NAMES 'utf8'");
	$result = mysql_query($query);
    @$num_rows = mysql_num_rows($result);
    if($num_rows == 0) {
       //return 0;
    } else {
        $curimage=0;
        while($row = mysql_fetch_array($result))
        {
			$tmparray = array();
            $file = $row['path'];
            $thumb = $row['thumb'];
			$width = $row['width'];
			$event_id = $row['event_id'];
			$height = $row['height'];
            $description = $row['comment'];
			$tmparray[] = $curimage;
			$tmparray[] = $file;
			$tmparray[] = $eventid;
			$tmparray[] = $description;
			$tmparray[] = $width;
			$tmparray[] = $height;
			$tmparray[] = $thumb;
            //echo "		[$curimage, \"$file\", \"$event_id\", \"$description\", \"$width\", \"$height\"],\n";
			$array_images[] = $tmparray;
            $curimage++;
        }
		$tmparray = array("placeholder");
		$array_images[] = $tmparray;
        //echo "		[\"placeholder\"]\n";
		//return $array_images;
    }
	$result_array = array("baseurl"=> "",
					"images" => $array_images,
					"desc" => array());
    //print_r($result_array);
	return $result_array;				
}
/*$eventid = 5;
        $query = $query = "SELECT * FROM event WHERE event_id = $eventid  and is_deleted = 0";
        mysql_query ("SET NAMES 'utf8'");
        $result = mysql_query($query);
        //@$num_rows = mysql_num_rows($result);
        //echo $num_rows;
        $row = mysql_fetch_array($result); //
        $albumdata = load_eventalbum($eventid);
        $return_data = array("path" => $row['path'],
                       "info" => $row['info'],
					   "albumdata" => $albumdata);
        echo (json_encode($return_data));*/
//initialize_calendar();
//build_contextmenu();
//echo (json_encode($events_by_day));
//get_eventinfo(15, 5, 2011);
?>